import pygame
import sys

# 初始化Pygame
pygame.init()

# 设置窗口大小
screen_width = 640
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("五子棋")

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)

# 棋盘参数
board_size = 15
cell_size = screen_width // board_size

# 初始化棋盘
board = [[None for _ in range(board_size)] for _ in range(board_size)]

# 绘制棋盘
def draw_board():
    screen.fill(white)
    # 绘制横向线条
    for y in range(board_size):
        start_pos = (0, y * cell_size)
        end_pos = (screen_width, y * cell_size)
        pygame.draw.line(screen, black, start_pos, end_pos, 1)
    # 绘制纵向线条
    for x in range(board_size):
        start_pos = (x * cell_size, 0)
        end_pos = (x * cell_size, screen_height)
        pygame.draw.line(screen, black, start_pos, end_pos, 1)

# 检查是否有玩家赢了
def check_winner(player):
    directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
    for direction in directions:
        for x in range(board_size):
            for y in range(board_size):
                if board[y][x] == player:
                    count = 1
                    for step in range(1, 5):
                        new_x = x + direction[0] * step
                        new_y = y + direction[1] * step
                        if 0 <= new_x < board_size and 0 <= new_y < board_size and board[new_y][new_x] == player:
                            count += 1
                        else:
                            break
                    if count >= 5:
                        return True
    return False

# 主循环
current_player = 'X'
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            col = x // cell_size
            row = y // cell_size
            if board[row][col] is None:
                board[row][col] = current_player
                if check_winner(current_player):
                    print(f"Player {current_player} wins!")
                    running = False
                current_player = 'O' if current_player == 'X' else 'X'

    draw_board()

    # 绘制棋子
    for row in range(board_size):
        for col in range(board_size):
            if board[row][col] is not None:
                color = red if board[row][col] == 'X' else green
                pos = (col * cell_size + cell_size // 2, row * cell_size + cell_size // 2)
                radius = cell_size // 4
                pygame.draw.circle(screen, color, pos, radius)

    pygame.display.flip()

# 清理并退出Pygame
pygame.quit()
sys.exit()